package cn.sc.summer.exception.util.ip;

import cn.sc.summer.constant.util.BaseIpUtil;
import cn.sc.summer.exception.exceptions.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 类名：针对请求获取ip地址值，并进行转换hash
 *
 * @author a-xin
 * @date 2023/7/27 16:10
 */
@Slf4j
@Component
public class IPUtil extends BaseIpUtil {

    /**
     * 获取请求体的真是IP地址(若被代理，则获取真实IP)
     *
     * @param request 请求体
     * @return ip地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        String unknown = "unknown";
        final String IPV_4 = "127.0.0.1";
        final String IPV_6 = "0:0:0:0:0:0:0:1";
        if (ipAddress == null || ipAddress.length() == 0 || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (IPV_4.equals(ipAddress) || IPV_6.equals(ipAddress)) {
                ///根据网卡取本机配置的IP
                try {
                    InetAddress inet = InetAddress.getLocalHost();
                    if (inet != null) {
                        ipAddress = inet.getHostAddress();
                    }
                } catch (Exception e) {
                    throw new CommonException("IP address acquisition exception: ", e);
                }
            }
        }
        if (IPV_4.equals(ipAddress) || IPV_6.equals(ipAddress)) {
            ///根据网卡取本机配置的IP
            try {
                InetAddress inet = InetAddress.getLocalHost();
                if (inet != null) {
                    ipAddress = inet.getHostAddress();
                }
            } catch (Exception e) {
                throw new CommonException("IP address acquisition exception: ", e);
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        String split = ",";
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(split) > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(split));
            }
        }
        return ipAddress;
    }

    /**
     * 测试网址连通性
     *
     * @param urlAddress 需要测试的网址
     * @return 测试结果返回
     */
    public static IpAddressResult checkIpAddress(String urlAddress) {
        try {
            IpAddressResult ipAddressResult = new IpAddressResult();
            long startTime = System.currentTimeMillis();
            URL url = new URL(urlAddress);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            ipAddressResult.setRespCode(responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                long endTime = System.currentTimeMillis();
                long latency = endTime - startTime;
                ipAddressResult.setSuccess(Boolean.TRUE);
                ipAddressResult.setLatency(latency);
            } else {
                ipAddressResult.setSuccess(Boolean.FALSE);
                ipAddressResult.setFailMessage(connection.getResponseMessage());
            }
            connection.disconnect();

            ipAddressResult.setAddress(urlAddress);
            ipAddressResult.setMethod("GET");
            return ipAddressResult;
        } catch (IOException e) {
            throw new CommonException(e.getMessage());
        }
    }

    /**
     * 检测ip地址是否能ping通
     *
     * @param ipAddress ping的地址
     * @param pingCount ping的次数
     * @param timeout   超时时间
     * @return 结果信息
     */
    public static PingIpAddressResult checkIpAddress(String ipAddress, Long pingCount, Long timeout) {
        try {
            String os = System.getProperty("os.name").toLowerCase();
            String pingCommand = os.contains("win") ? "ping -n " + pingCount + " -w " + timeout + " " + ipAddress : "ping -c " + pingCount + " -W " + timeout + " " + ipAddress;
            // 执行ping命令
            Process process = Runtime.getRuntime().exec(pingCommand);
            BufferedReader reader = os.contains("win") ?
                    new BufferedReader(new InputStreamReader(process.getInputStream(), "gbk"))
                    : new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));

            String line;
            int packetSent = 0;
            int packetReceived = 0;
            double totalResponseTime = 0;
            PingIpAddressResult pingIpAddressResult = new PingIpAddressResult();

            // 读取ping命令输出
            while ((line = reader.readLine()) != null) {
                log.info(line);
                // 解析ping命令输出，获取丢包率和响应时间
                // 来自 192.168.1.9 的回复: 字节=32 时间=1ms TTL=64
                if (os.contains("win") && line.contains("时间=")) {
                    packetSent++;
                    packetReceived++;
                    int startIndex = line.indexOf("时间=") + 3;
                    int endIndex = line.indexOf("ms");
                    double responseTime = Double.parseDouble(line.substring(startIndex, endIndex).trim());
                    totalResponseTime += responseTime;
                } else if (line.contains("time=")) {
                    packetSent++;
                    packetReceived++;
                    int startIndex = line.indexOf("time=") + 5;
                    int endIndex = line.indexOf(" ms");
                    String trim = line.substring(startIndex, endIndex).trim();
                    double responseTime = Double.parseDouble(trim);
                    totalResponseTime += responseTime;
                } else if (os.contains("linux") && line.contains("时间=")) {
                    packetSent++;
                    packetReceived++;
                    int startIndex = line.indexOf("时间=") + 3;
                    int endIndex = line.indexOf(" 毫秒");
                    double responseTime = Double.parseDouble(line.substring(startIndex, endIndex).trim());
                    totalResponseTime += responseTime;
                } else if (line.contains("已发送") && line.contains("已接收")) {
                    Pattern packetPattern = Pattern.compile("(\\d+) 个包");
                    Matcher packetMatcher = packetPattern.matcher(line);
                    if (packetMatcher.find()) {
                        packetSent = Integer.parseInt(packetMatcher.group(1));
                    }
                    Pattern lossPattern = Pattern.compile("(\\d+)% 包丢失");
                    Matcher lossMatcher = lossPattern.matcher(line);
                    if (lossMatcher.find()) {
                        int packetLossPercentage = Integer.parseInt(lossMatcher.group(1));
                        packetReceived = packetSent - (packetSent * packetLossPercentage) / 100;
                    }
                }
            }
            if (packetSent > 0) {
                double packetLossRate = (packetSent - packetReceived) / (double) packetSent * 100;
                double averageResponseTime = totalResponseTime / (double) packetReceived;
                pingIpAddressResult.setAccessibility(Boolean.TRUE);
                pingIpAddressResult.setResponseTime(averageResponseTime);
                pingIpAddressResult.setPacketLoss(packetLossRate);
            } else {
                pingIpAddressResult.setAccessibility(Boolean.FALSE);
                pingIpAddressResult.setPacketLoss(100D);
            }
            return pingIpAddressResult;
        } catch (IOException e) {
            throw new CommonException(e.getMessage());
        }
    }

}
